package com.jlc.o2o.web.shopadmin;

import com.dyuproject.protostuff.Output;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jlc.o2o.dto.ShopExecuption;
import com.jlc.o2o.entity.Area;
import com.jlc.o2o.entity.PersonInfo;
import com.jlc.o2o.entity.Shop;
import com.jlc.o2o.entity.ShopCategory;
import com.jlc.o2o.enums.ShopSateEnum;
import com.jlc.o2o.service.AreaService;
import com.jlc.o2o.service.ShopCategoryService;
import com.jlc.o2o.service.ShopService;
import com.jlc.o2o.service.impl.AreaServiceImpl;
import com.jlc.o2o.util.HttpServletRequestUtil;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {

    Logger logger = LoggerFactory.getLogger(ShopManagementController.class);
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;

    @RequestMapping(value = "/shopoperation", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getShopInitInfo() {
        Map<String, Object> modelMap = new HashMap<>();
        List<ShopCategory> shopCategoryList = new ArrayList<>();
        List<Area> areaList = new ArrayList<>();
        try {
            shopCategoryList = shopCategoryService.getShopCategory(new ShopCategory());
            areaList = areaService.queryArea();
/*            logger.error(areaList.toString() + "-----------------------------------------------------------------");*/
            modelMap.put("shopCategoryList", shopCategoryList);
/*            logger.error(shopCategoryList.size() + "-----------------------------------------------------------------");*/
            modelMap.put("areaList", areaList);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }
        return modelMap;
    }


    @RequestMapping(value = "/registerShop", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        //接收并转化相应的参数， 包括店铺信息以及图片信息
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            //将用户传入的信息使用json转化为对象
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }

        CommonsMultipartFile shopImg = null;
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 设置编码
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        // 判断 request 是否有文件上传,即多部分请求...
        if (commonsMultipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            // shopImg 是指 文件上传标签的 name=值
            // 根据 name 获取上传的文件..
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "上传图片不能为空");
            return modelMap;
        }
        //2.注册店铺
        if (shop != null && shopImg != null) {
            PersonInfo owner = new PersonInfo();
            owner.setUserId(1L);
            shop.setOwner(owner);
            ShopExecuption shopExecuption = shopService.addShop(shop, shopImg);
            if (shopExecuption.getState() == ShopSateEnum.CHECK.getState()) {
                modelMap.put("success", true);
            } else {
                modelMap.put("success", false);
                modelMap.put("errMsg", shopExecuption.getStateInfo());
            }


        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "上传店铺信息不能为空");
            return modelMap;
        }

        return modelMap;
    }


    //CommonsMultipartFile 与 File 互转要用到
   /* private static void inputStreamToFile(InputStream inputStream, File file) {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] b = new byte[1024];
            while ((bytesRead = inputStream.read(b)) != -1) {
                os.write(b, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new RuntimeException("调用inputStream异常" + e.getMessage());
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("关闭inputStream异常" + e.getMessage());
            }

        }

    }*/
}
